<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\PermissionTypeConstants;
use App\Common\Constants\SmsEventConstants;
use App\Common\Mapper\CommonRoleMapper;
use App\Common\Service\CommonMenuService;
use App\Common\Service\CommonRoleService;
use App\Common\Service\SmsService;
use App\CustHub\Constants\MsgTypeConstants;
use App\CustHub\Interfaces\ChUserServiceInterface;
use App\CustHub\Mapper\ChMaterialMapper;
use App\CustHub\Mapper\ChUserMapper;
use App\CustHub\Model\ChMaterial;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChUser;
use App\Setting\Service\SettingConfigService;
use Carbon\Carbon;
use Humx\HyperfSms\Contract\SmsInterface;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\Redis\RedisFactory;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\DependProxy;
use Mine\Annotation\Transaction;
use Mine\Exception\MineException;
use Mine\Helper\Str;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ChMaterialService extends AbstractService
{
    public $mapper;
    public function __construct(ChMaterialMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function autoCollect(ChRobot $robotInfo,$data)
    {
        $mainUid=$robotInfo->main_uid;
        $uid=$robotInfo->uid;
        //个人收录配置
        $material_collect_person_config = container()->get(ChConfigService::class)->getConfigByGroupKey($uid,$mainUid,'material_collect_person_config');
        $content=$data['content'];
        if($data['content']['msg_type'] == MsgTypeConstants::URL ||
            $data['content']['msg_type'] == MsgTypeConstants::VIDEO_CHANNEL ||
            $data['content']['msg_type'] == MsgTypeConstants::MINI_PROGRAM){
            $content=[
                'content'=>$data['msg_data'],
                'msg_type'=>$data['content']['msg_type']
            ];
        }
        if($data['content']['msg_type'] == MsgTypeConstants::FILE || $data['content']['msg_type'] == MsgTypeConstants::VIDEO || $data['content']['msg_type'] == MsgTypeConstants::IMAGE){
            if(empty($content['content'])) return;
        }
        logger()->info('自动收录素材-机器人'.$robotInfo->id);
        //logger()->info('自动收录素材-配置'.json_encode($material_collect_person_config));
        //logger()->info('自动收录素材-收录内容'.json_encode($data));
        $isRobot=$data['is_robot'];
        if(!empty($material_collect_person_config['material_collect_person_config']['value'])){
            $cfg=json_decode($material_collect_person_config['material_collect_person_config']['value'],true);
            //本人收录
            if($isRobot && $data['sender'] == $data['receiver']  && !empty($cfg['self_collect']) && $cfg['self_collect'] == 1 && !$data['is_room']){
                $saveData = [
                    'title' => '未命名素材',
                    'content' =>  [
                        $content
                    ],
                    'is_personal' => 0,
                    'robot_id' => $robotInfo->id
                ];
                logger()->info('自动收录素材-个人收录-素材库内容'.json_encode($saveData));
                ChMaterial::saveMaterial($uid,$mainUid,$saveData);
            }

            //群收录
            if($data['is_room'] && !$isRobot){
                if(!empty($cfg['room_collect']) && $cfg['room_collect'] == 1){
                    $roomIds = array_column($cfg['room_config'],'room_wxid');
                    logger()->info('自动收录素材-群收录-群ids'.json_encode($roomIds));
                    if(in_array($data['from_room_id'],$roomIds)){
                        $filteredConfig = array_filter($cfg['room_config'], function($room)use($data){
                            return $room['room_wxid'] == $data['from_room_id'];
                        });
                        if(!empty($filteredConfig[0])){
                            $filteredConfig=$filteredConfig[0];
                            //collect_type 1=企业 2=个人
                            $is_personal=$filteredConfig['collect_type'] == 1?0:1;
                            $saveData = [
                                'title' => '未命名素材',
                                'content' =>  [
                                    $content
                                ],
                                'is_personal' => $is_personal,
                                'robot_id' => $robotInfo->id
                            ];
                            if(!empty($filteredConfig['tags'])){
                                $saveData['tags']=$filteredConfig['tags'];
                            }
                            logger()->info('自动收录素材-群收录-素材库内容'.json_encode($saveData));
                            ChMaterial::saveMaterial($uid,$mainUid,$saveData);
                        }
                    }
                }
            }
        }
    }

}